#pragma once
#include <iostream>
#include <sys/types.h>
#include<string>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "Log.hpp"
#include "Init.hpp"
const std::string sep = " ";                  //分隔符

class Task
{
    InitCommand command;

public:
    Task(int sockfd, std::string ip, uint16_t port)
        : _sockfd(sockfd), _ip(ip), _port(port)
    {
    }
    Task()
    {}
    std::string Splict(const std::string& cmd)
    {
        int pos=cmd.find(sep);
        std::string ret=cmd.substr(0,pos);
        return ret;
    }
    void run()
    {
        char buffer[1024];
        int n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout<<"client# "<<buffer<<std::endl;
            std::string response = "server# ";
            //这里需要取收到命令的首部，用于在安全命令内查找
            std::string prevcmd=Splict(buffer);
            //查找
            //查找失败
            if(!command.find(prevcmd))
            {
                response+="坏人";
            }
            //查找成功，执行
            else
            {
                response+=command.excute(buffer);
            }
            write(_sockfd, response.c_str(), response.size());
        }
        else
        {
            Log(WARNING, "already disconnect!");
        }
        close(_sockfd);
    }
    void operator()()
    {
        run();
    }
    ~Task(){}
private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
};